package com.comtop.springboot.templet.common.xss;

import com.comtop.springboot.templet.common.exception.CustomException;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * SQL过滤
 * @author wangjiafang
 * @version 1.0
 * @since 2017-04-01 16:16
 */
public class SQLFilter {

    /**
     * SQL注入过滤
     * @param str  待验证的字符串
     */
    public static String sqlInject(String str){
        if(StrUtil.isBlank(str)){
            return null;
        }
        //去掉'|"|;|\字符
        str = StrUtil.removeAll(str, "'");
        str = StrUtil.removeAll(str, "\"");
        str = StrUtil.removeAll(str, ";");
        str = StrUtil.removeAll(str, "\\");

        //转换成小写
        str = str.toLowerCase();

        //非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alert", "drop"};

        //判断是否包含非法字符
        for(String keyword : keywords){
            if(str.indexOf(keyword) != -1){
                throw new CustomException("包含非法字符");
            }
        }

        return str;
    }
}
